

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';
import Header from '../../components/Header';

// 后端返回的内容数据结构
interface ContentVO {
  id: number;
  title: string;
  description: string;
  content: string;
  contentType: string;
  category: string;
  tags: string[];
  imageUrl: string;
  videoUrl: string;
  duration: number;
  difficulty: number;
  status: number;
  viewCount: number;
  likeCount: number;
  collectCount: number;
  createTime: string;
  updateTime: string;
  isFeatured: number; // 是否精选：0-否，1-是
  user: {
    id: number;
    userName: string;
    userAvatar: string;
  };
  hasLiked: boolean;
  hasCollected: boolean;
}

// 分页响应结构
interface PageResponse<T> {
  records: T[];
  total: number;
  size: number;
  current: number;
  pages: number;
}

// API响应结构
interface ApiResponse<T> {
  code: number;
  data: T;
  message: string;
}

// 前端展示用的精选内容项结构
interface FeaturedContentItem {
  id: string;
  title: string;
  description: string;
  category: string;
  views: string;
  likes: string;
  publishTime: string;
  imageUrl: string;
}

const HomePage: React.FC = () => {
  const [featuredContent, setFeaturedContent] = useState<FeaturedContentItem[]>([]);
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 工具函数
  const formatNumber = (num: number): string => {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万';
    } else if (num >= 1000) {
      return (num / 1000).toFixed(1) + 'k';
    }
    return num.toString();
  };

  const formatTime = (timeStr: string): string => {
    const now = new Date();
    const time = new Date(timeStr);
    const diff = now.getTime() - time.getTime();
    
    const minutes = Math.floor(diff / (1000 * 60));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    
    if (minutes < 60) {
      return `${minutes}分钟前`;
    } else if (hours < 24) {
      return `${hours}小时前`;
    } else {
      return `${days}天前`;
    }
  };

  const getCategoryBgColor = (category: string): string => {
    switch (category) {
      case '认知提升':
      case 'cognition':
        return 'bg-secondary';
      case '身体健身':
      case 'fitness':
        return 'bg-green-500';
      case '学习能力':
      case 'learning':
        return 'bg-purple-500';
      default:
        return 'bg-gray-500';
    }
  };

  // 获取精选内容
  const fetchFeaturedContent = async () => {
    try {
      setLoading(true);
      console.log('开始获取精选内容...');

      const queryParams = {
        current: 1,
        pageSize: 6, // 获取6个精选内容
        isFeatured: 1 // 只获取精选内容
      };

      console.log('发送精选内容API请求:', queryParams);

      const response = await fetch('/api/content/list/page/vo', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(queryParams),
      });

      console.log('精选内容API响应状态:', response.status);

      if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
      }

      const result: ApiResponse<PageResponse<ContentVO>> = await response.json();
      
      console.log('精选内容API响应数据:', result);
      
      if (result.code === 0) {
        // 转换数据格式
        const items: FeaturedContentItem[] = result.data.records.map(item => ({
          id: (item.id || 0).toString(),
          title: item.title || '未知标题',
          description: item.description || '暂无描述',
          category: (item.tags && item.tags.length > 0) ? item.tags[0] : item.category || '精选内容',
          views: formatNumber(item.viewCount || 0) + '次',
          likes: formatNumber(item.likeCount || 0),
          publishTime: formatTime(item.createTime || new Date().toISOString()),
          imageUrl: item.imageUrl || 'https://s.coze.cn/image/quHpKpndnNo/'
        }));

        setFeaturedContent(items);
        console.log('成功获取精选内容:', items.length, '条');
      } else {
        console.error('获取精选内容失败:', result.message);
        // 如果API调用失败，使用默认数据
        setFeaturedContent(getDefaultFeaturedContent());
      }
    } catch (error) {
      console.error('获取精选内容时发生错误:', error);
      // 发生错误时使用默认数据
      setFeaturedContent(getDefaultFeaturedContent());
    } finally {
      setLoading(false);
    }
  };

  // 默认精选内容数据
  const getDefaultFeaturedContent = (): FeaturedContentItem[] => [
    {
      id: '1',
      title: '批判性思维：如何建立理性思考框架',
      description: '掌握批判性思维的核心方法，学会独立思考和理性判断，提升决策质量。',
      category: '认知提升',
      views: '1.2万次',
      likes: '856',
      publishTime: '2天前',
      imageUrl: 'https://s.coze.cn/image/Dqsq0fYEc_w/'
    },
    {
      id: '2',
      title: '30天全身训练计划：从零开始塑造完美身材',
      description: '科学的训练计划，适合初学者的全身锻炼方案，帮助你建立运动习惯。',
      category: '身体健身',
      views: '8.9千次',
      likes: '623',
      publishTime: '1天前',
      imageUrl: 'https://s.coze.cn/image/e00PwbJkk6A/'
    },
    {
      id: '3',
      title: '费曼学习法：如何快速掌握新知识',
      description: '通过费曼技巧，学会用简单的语言解释复杂概念，加深理解和记忆。',
      category: '学习能力',
      views: '15.6万次',
      likes: '2.1千',
      publishTime: '3天前',
      imageUrl: 'https://s.coze.cn/image/xwbkahQ-Jpo/'
    }
  ];

  useEffect(() => {
    const originalTitle = document.title;
    document.title = '精进坊 - 个人成长伙伴';
    
    // 获取精选内容
    fetchFeaturedContent();
    
    return () => { document.title = originalTitle; };
  }, []);

  const handleTagClick = (tag: string) => {
    navigate(`/search-result?tag=${encodeURIComponent(tag)}`);
  };

  const handleFeaturedCardClick = (id: string) => {
    navigate(`/content-detail?id=${id}`);
  };

  const handleLatestItemClick = (id: string) => {
    navigate(`/content-detail?id=${id}`);
  };

  const handleSectionClick = (section: string) => {
    navigate(`/${section}-home`);
  };

  const handleStartButtonClick = (e: React.MouseEvent, section: string) => {
    e.stopPropagation();
    navigate(`/${section}-home`);
  };

  const handleViewMoreClick = () => {
    navigate('/search-result');
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 使用通用头部组件 */}
      <Header currentPage="home" />

      {/* 主布局容器 */}
      <div className="pt-16 min-h-screen">
        {/* 主内容区 */}
        <main className="p-6">
          {/* 页面头部 */}
          <div className="mb-8">
            <div className="flex items-center justify-between">
              <div>
                <h2 className="text-2xl font-bold text-text-primary mb-2">欢迎回来，张三！</h2>
                <nav className="text-sm text-text-secondary">
                  <span>首页</span>
                </nav>
              </div>
              <div className="flex items-center space-x-6">
                <div className="text-center">
                  <div className="text-2xl font-bold text-secondary">156</div>
                  <div className="text-xs text-text-secondary">学习时长(小时)</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-accent">23</div>
                  <div className="text-xs text-text-secondary">完成课程</div>
                </div>
                <div className="text-center">
                  <div className="text-2xl font-bold text-green-500">7</div>
                  <div className="text-xs text-text-secondary">连续天数</div>
                </div>
              </div>
            </div>
          </div>

          {/* 精选内容推荐区 */}
          <section className="mb-8">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-semibold text-text-primary">精选推荐</h3>
              <button onClick={handleViewMoreClick} className="text-secondary hover:text-accent text-sm font-medium">
                查看更多 <i className="fas fa-arrow-right ml-1"></i>
              </button>
            </div>
            
            {loading ? (
              <div className="flex items-center justify-center py-12">
                <div className="text-center">
                  <i className="fas fa-spinner fa-spin text-2xl text-secondary mb-2"></i>
                  <p className="text-text-secondary">正在加载精选内容...</p>
                </div>
              </div>
            ) : (
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                {featuredContent.map((item, index) => (
                  <div 
                    key={item.id} 
                    onClick={() => handleFeaturedCardClick(item.id)} 
                    className={`${styles.contentCard} rounded-card shadow-card ${styles.cardHover} cursor-pointer`}
                  >
                    <div className="relative">
                      <img 
                        src={item.imageUrl} 
                        alt={item.title} 
                        className="w-full h-48 object-cover rounded-t-card" 
                      />
                      <div className={`absolute top-3 left-3 ${getCategoryBgColor(item.category)} text-white px-2 py-1 rounded-full text-xs font-medium`}>
                        {item.category}
                      </div>
                    </div>
                    <div className="p-5">
                      <h4 className="font-semibold text-text-primary mb-2 line-clamp-2">{item.title}</h4>
                      <p className="text-text-secondary text-sm mb-4 line-clamp-2">{item.description}</p>
                      <div className="flex items-center justify-between">
                        <div className="flex items-center space-x-4 text-xs text-text-secondary">
                          <span><i className="fas fa-play mr-1"></i>{item.views}</span>
                          <span><i className="fas fa-heart mr-1"></i>{item.likes}</span>
                        </div>
                        <span className="text-xs text-text-secondary">{item.publishTime}</span>
                      </div>
                    </div>
                  </div>
                ))}
                
                {/* 如果没有精选内容，显示提示 */}
                {featuredContent.length === 0 && (
                  <div className="col-span-full text-center py-12">
                    <i className="fas fa-star text-4xl text-gray-300 mb-4"></i>
                    <p className="text-text-secondary">暂无精选内容</p>
                  </div>
                )}
              </div>
            )}
          </section>

          {/* 三大板块入口区 */}
          <section className="mb-8">
            <h3 className="text-xl font-semibold text-text-primary mb-6">开始你的成长之旅</h3>
            
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              {/* 认知提升板块 */}
              <div onClick={() => handleSectionClick('cognition')} className={`${styles.contentCard} rounded-card shadow-card ${styles.cardHover} cursor-pointer`}>
                <div className="p-6 text-center">
                  <div className={`w-16 h-16 mx-auto mb-4 ${styles.gradientBg} rounded-full flex items-center justify-center`}>
                    <i className="fas fa-brain text-white text-2xl"></i>
                  </div>
                  <h4 className="text-lg font-semibold text-text-primary mb-2">认知提升</h4>
                  <p className="text-text-secondary text-sm mb-4">思维模型 · 心理学 · 决策能力</p>
                  <div className="flex items-center justify-center space-x-4 text-xs text-text-secondary mb-4">
                    <span><i className="fas fa-book mr-1"></i>126篇文章</span>
                    <span><i className="fas fa-video mr-1"></i>48个视频</span>
                  </div>
                  <button onClick={(e) => handleStartButtonClick(e, 'cognition')} className="w-full py-2 bg-secondary text-white rounded-lg hover:bg-accent transition-colors">
                    开始学习
                  </button>
                </div>
              </div>

              {/* 身体健身板块 */}
              <div onClick={() => handleSectionClick('fitness')} className={`${styles.contentCard} rounded-card shadow-card ${styles.cardHover} cursor-pointer`}>
                <div className="p-6 text-center">
                  <div className="w-16 h-16 mx-auto mb-4 bg-gradient-to-br from-green-400 to-green-600 rounded-full flex items-center justify-center">
                    <i className="fas fa-dumbbell text-white text-2xl"></i>
                  </div>
                  <h4 className="text-lg font-semibold text-text-primary mb-2">身体健身</h4>
                  <p className="text-text-secondary text-sm mb-4">训练计划 · 营养知识 · 康复指导</p>
                  <div className="flex items-center justify-center space-x-4 text-xs text-text-secondary mb-4">
                    <span><i className="fas fa-book mr-1"></i>89篇文章</span>
                    <span><i className="fas fa-video mr-1"></i>67个视频</span>
                  </div>
                  <button onClick={(e) => handleStartButtonClick(e, 'fitness')} className="w-full py-2 bg-green-500 text-white rounded-lg hover:bg-green-600 transition-colors">
                    开始训练
                  </button>
                </div>
              </div>

              {/* 学习能力板块 */}
              <div onClick={() => handleSectionClick('learning')} className={`${styles.contentCard} rounded-card shadow-card ${styles.cardHover} cursor-pointer`}>
                <div className="p-6 text-center">
                  <div className="w-16 h-16 mx-auto mb-4 bg-gradient-to-br from-purple-400 to-purple-600 rounded-full flex items-center justify-center">
                    <i className="fas fa-book text-white text-2xl"></i>
                  </div>
                  <h4 className="text-lg font-semibold text-text-primary mb-2">学习能力</h4>
                  <p className="text-text-secondary text-sm mb-4">记忆方法 · 时间管理 · 技能习得</p>
                  <div className="flex items-center justify-center space-x-4 text-xs text-text-secondary mb-4">
                    <span><i className="fas fa-book mr-1"></i>156篇文章</span>
                    <span><i className="fas fa-video mr-1"></i>52个视频</span>
                  </div>
                  <button onClick={(e) => handleStartButtonClick(e, 'learning')} className="w-full py-2 bg-purple-500 text-white rounded-lg hover:bg-purple-600 transition-colors">
                    提升技能
                  </button>
                </div>
              </div>
            </div>
          </section>

          {/* 最新内容动态区 */}
          <section className="mb-8">
            <div className="flex items-center justify-between mb-6">
              <h3 className="text-xl font-semibold text-text-primary">最新动态</h3>
              <button onClick={handleViewMoreClick} className="text-secondary hover:text-accent text-sm font-medium">
                查看全部 <i className="fas fa-arrow-right ml-1"></i>
              </button>
            </div>
            
            <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
              {/* 最新内容列表 */}
              <div className="space-y-4">
                {/* 最新内容项1 */}
                <div onClick={() => handleLatestItemClick('10')} className={`${styles.contentCard} rounded-card shadow-card p-4 ${styles.cardHover} cursor-pointer`}>
                  <div className="flex space-x-4">
                    <img src="https://s.coze.cn/image/V8fquGrhI9c/" 
                         alt="最新内容缩略图" className="w-20 h-20 object-cover rounded-lg" />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-secondary text-white px-2 py-1 rounded-full text-xs">认知提升</span>
                        <span className="text-xs text-text-secondary">5分钟前</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1 line-clamp-2">如何运用第一性原理进行创新思考</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">深度解析埃隆·马斯克的思维模式，学会从根本上解决问题的方法。</p>
                    </div>
                  </div>
                </div>

                {/* 最新内容项2 */}
                <div onClick={() => handleLatestItemClick('11')} className={`${styles.contentCard} rounded-card shadow-card p-4 ${styles.cardHover} cursor-pointer`}>
                  <div className="flex space-x-4">
                    <img src="https://s.coze.cn/image/jF6SY2gFOVk/" 
                         alt="最新内容缩略图" className="w-20 h-20 object-cover rounded-lg" />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-green-500 text-white px-2 py-1 rounded-full text-xs">身体健身</span>
                        <span className="text-xs text-text-secondary">1小时前</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1 line-clamp-2">HIIT高强度间歇训练的科学原理</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">了解HIIT训练的生理机制，制定高效的燃脂计划。</p>
                    </div>
                  </div>
                </div>

                {/* 最新内容项3 */}
                <div onClick={() => handleLatestItemClick('12')} className={`${styles.contentCard} rounded-card shadow-card p-4 ${styles.cardHover} cursor-pointer`}>
                  <div className="flex space-x-4">
                    <img src="https://s.coze.cn/image/WVm4ZG3KJ80/" 
                         alt="最新内容缩略图" className="w-20 h-20 object-cover rounded-lg" />
                    <div className="flex-1">
                      <div className="flex items-center space-x-2 mb-1">
                        <span className="bg-purple-500 text-white px-2 py-1 rounded-full text-xs">学习能力</span>
                        <span className="text-xs text-text-secondary">3小时前</span>
                      </div>
                      <h4 className="font-medium text-text-primary mb-1 line-clamp-2">番茄工作法：提升专注力的实用技巧</h4>
                      <p className="text-text-secondary text-sm line-clamp-2">掌握时间管理的核心方法，告别拖延症，提高工作效率。</p>
                    </div>
                  </div>
                </div>
              </div>

              {/* 热门标签和统计 */}
              <div className="space-y-6">
                {/* 热门标签 */}
                <div className={`${styles.contentCard} rounded-card shadow-card p-5`}>
                  <h4 className="font-semibold text-text-primary mb-4">热门标签</h4>
                  <div className="flex flex-wrap gap-2">
                    <span onClick={() => handleTagClick('思维模型')} className="bg-primary text-secondary px-3 py-1 rounded-full text-sm cursor-pointer hover:bg-secondary hover:text-white transition-colors">思维模型</span>
                    <span onClick={() => handleTagClick('健身计划')} className="bg-gray-100 text-text-secondary px-3 py-1 rounded-full text-sm cursor-pointer hover:bg-secondary hover:text-white transition-colors">健身计划</span>
                    <span onClick={() => handleTagClick('记忆方法')} className="bg-gray-100 text-text-secondary px-3 py-1 rounded-full text-sm cursor-pointer hover:bg-secondary hover:text-white transition-colors">记忆方法</span>
                    <span onClick={() => handleTagClick('时间管理')} className="bg-gray-100 text-text-secondary px-3 py-1 rounded-full text-sm cursor-pointer hover:bg-secondary hover:text-white transition-colors">时间管理</span>
                    <span onClick={() => handleTagClick('营养知识')} className="bg-gray-100 text-text-secondary px-3 py-1 rounded-full text-sm cursor-pointer hover:bg-secondary hover:text-white transition-colors">营养知识</span>
                    <span onClick={() => handleTagClick('心理学')} className="bg-gray-100 text-text-secondary px-3 py-1 rounded-full text-sm cursor-pointer hover:bg-secondary hover:text-white transition-colors">心理学</span>
                  </div>
                </div>

                {/* 今日学习数据 */}
                <div className={`${styles.contentCard} rounded-card shadow-card p-5`}>
                  <h4 className="font-semibold text-text-primary mb-4">今日学习</h4>
                  <div className="space-y-3">
                    <div className="flex justify-between items-center">
                      <span className="text-text-secondary">学习时长</span>
                      <span className="font-medium text-text-primary">2小时36分</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-text-secondary">完成内容</span>
                      <span className="font-medium text-text-primary">3篇文章</span>
                    </div>
                    <div className="flex justify-between items-center">
                      <span className="text-text-secondary">新收藏</span>
                      <span className="font-medium text-text-primary">2个</span>
                    </div>
                  </div>
                  <div className="mt-4 pt-4 border-t border-gray-100">
                    <div className="text-center">
                      <div className="text-2xl font-bold text-secondary mb-1">7</div>
                      <div className="text-xs text-text-secondary">连续学习天数</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>
        </main>
      </div>
    </div>
  );
};

export default HomePage;

